<?php

namespace App\Jobs;

use App\Http\Helpers\Sign;
use App\Http\Services\ApiService;
use App\Http\Services\MsgService;
use App\Models\School;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class UpdateSchoolJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $schoolCode;
    public $host;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($schoolCode, $host)
    {
        $this->schoolCode = $schoolCode;
        $this->host = $host;
        Sign::writeLog("更新{$schoolCode}数据", $schoolCode .'_'. $host, 'job');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Sign::writeLog("start", date('Y-m-d H:i:s', time()), 'job');

        $school = School::where('code', $this->schoolCode)
            ->first();
        if(empty($school)){
            $school = new School();
            $school->code = $this->schoolCode;
        }
        Sign::writeLog(__CLASS__.'/'.__LINE__, $school, 'job');
        $result = ApiService::getSchoolInfo($this->schoolCode, $this->host);

        Sign::writeLog(__CLASS__.'/'.__LINE__, $result, 'job');
        if(empty($result) || $result['code'] != 0 || empty($result['school_info'])){
            return MsgService::getMsg(1008);
        }
        $schoolInfo = $result['school_info'];
        //更新主体信息
        $school->name = $schoolInfo['name'] ?? '';
        $school->badge = $schoolInfo['badge'] ?? '';
        $school->local_host = $schoolInfo['local_host'] ?? '';
        $school->local_deploy = $schoolInfo['local_deploy'] ?? 0;
        $school->gate_host = $schoolInfo['gate_host'] ?? '';
        $res = $school->save();
        if($res){
            Sign::writeLog(__CLASS__.'/'.__LINE__, $this->schoolCode .'更新成功！', 'job');
        }else{
            Sign::writeLog(__CLASS__.'/'.__LINE__, $this->schoolCode .'更新失败！', 'job');
        }
        Sign::writeLog("end", date('Y-m-d H:i:s', time()), 'job');
    }
}
